package com.ope.web.controller.laterhandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import com.ope.web.controller.chainresponsibility.TopicAnalysisHandle;
import com.ope.web.model.DTO.ProcessMointorRequestBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;




/**
 * 项目服务实现调度
 * @author  fxr
 * @date 2024年12月24日16:39:20
 */
@Component
@Slf4j
public class TopicHandleAnalysisSppp extends TopicAnalysisHandle {


    private static final String[] SERVICE_TYPE = {"sppp"};


    @Override
    public void process(ProcessMointorRequestBody processMointorRequestBody) {
        //进行服务检查并拉起
        dataReport(processMointorRequestBody);
    }

    /**
     * 项目服务实现
     * @param   processMointorRequestBody processMointorRequestBody
     * @date 2024年12月24日18:18:23
     */
    private void dataReport(ProcessMointorRequestBody processMointorRequestBody) {
        boolean isRunning = isProcessRunning(processMointorRequestBody.getProcessName());

        if (!isRunning) {
            // 这里写启动进程的代码，启动一个Java应用程序
             startProcess(processMointorRequestBody.getBatsh());
        }

    }

    public static boolean isProcessRunning(String processName) {
        try {
            // 使用系统命令来检查进程是否存在
            Process process = Runtime.getRuntime().exec(new String[]{"sh", "-c", "ps aux | grep " + processName});
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains(processName)) {
                    return true;
                }
            }
            process.waitFor();
            return false;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void startProcess(String command) {
        try {
            Process process = Runtime.getRuntime().exec(command);
            // 如果需要，可以从进程的输出中读取信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String[] getServiceTypes() {
        return SERVICE_TYPE;
    }

    @Override
    public Boolean matchDecoder(ProcessMointorRequestBody processMointorRequestBody, String serviceType) {
        String[] serviceTypes = getServiceTypes();
        if (Arrays.asList(serviceTypes).contains(serviceType)) {
            return true;
        }
        return false;
    }


}
